<template>
  <el-drawer v-model="visible" title="精准对比" direction="rtl" size="800px">
    <div class="p-6">
      <!-- 检查项目 -->
      <div class="mb-6">
        <div class="text-sm text-gray-600 mb-3">检查项目</div>
        <el-select
          v-model="selectedItem"
          placeholder="可输入检查项目进行搜索（如：血糖）"
          class="w-full"
          filterable
          :filter-method="filterItems"
          :loading="itemsLoading"
          clearable
        >
          <template #prefix>
            <el-icon class="text-gray-400">
              <Search />
            </el-icon>
          </template>
          <el-option
            v-for="item in filteredItems"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>

      <!-- 日期范围 -->
      <div class="mb-6">
        <div class="text-sm text-gray-600 mb-3">日期范围</div>
        <div class="flex flex-wrap gap-3">
          <el-button
            v-for="period in datePeriods"
            :key="period.value"
            :type="selectedPeriod === period.value ? 'primary' : 'default'"
            size="small"
            @click="handlePeriodChange(period.value)"
          >
            {{ period.label }}
          </el-button>
        </div>

        <!-- 自定义时间选择器 -->
        <div v-if="selectedPeriod === 'custom'" class="mt-4">
          <div class="text-xs text-gray-500 mb-2">选择时间范围</div>
          <el-date-picker
            v-model="customDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            class="w-full"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
          />
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="flex justify-center">
        <el-button
          type="primary"
          size="large"
          class="px-8"
          :loading="compareLoading"
          :disabled="!canCompare"
          @click="handleCompare"
        >
          去对比
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { computed, ref, watch, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import {
  reportApi,
  type CompareItemVO,
  type CompareItemResultVO
} from "@/api/report-api";
import { ElMessage } from "element-plus";

interface Props {
  modelValue?: boolean;
  userId?: number;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  userId: undefined
});

const emit = defineEmits<{
  "update:modelValue": [value: boolean];
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => {
    emit("update:modelValue", value);
  }
});
// 对比查询相关状态
const compareLoading = ref(false);
const compareResults = ref<CompareItemResultVO[]>([]);

// 计算是否可以进行对比
const canCompare = computed(() => {
  const hasSelectedItem = !!selectedItem.value;
  const hasValidDateRange =
    selectedPeriod.value !== "custom" ||
    (customDateRange.value[0] && customDateRange.value[1]);

  return hasSelectedItem && hasValidDateRange && props.userId;
});
// 获取时间范围
const getDateRange = (): { startTime: number; endTime: number } => {
  const today = new Date();
  const formatDate = (date: Date) => {
    return date.getTime();
  };

  if (selectedPeriod.value === "custom") {
    // 自定义时间需要转换为时间戳
    const startDate = new Date(customDateRange.value[0]);
    const endDate = new Date(customDateRange.value[1]);
    return {
      startTime: startDate.getTime(),
      endTime: endDate.getTime()
    };
  }

  // 计算预设时间范围
  const yearsMap: Record<string, number> = {
    "1year": 1,
    "2year": 2,
    "3year": 3,
    "5year": 5,
    "10year": 10
  };

  const years = yearsMap[selectedPeriod.value] || 1;
  const startDate = new Date(today);
  startDate.setFullYear(today.getFullYear() - years);

  return {
    startTime: formatDate(startDate),
    endTime: formatDate(today)
  };
};
// 处理对比查询
const handleCompare = async () => {
  if (!canCompare.value) {
    ElMessage.warning("请选择检查项目和时间范围");
    return;
  }

  try {
    compareLoading.value = true;
    const { startTime, endTime } = getDateRange();

    const response = await reportApi.queryCompareItemResult({
      userId: props.userId!,
      itemId: selectedItem.value!,
      startTime,
      endTime
    });

    if (response.code === 0 && response.data) {
      compareResults.value = response.data;
      ElMessage.success("查询成功");

      // 这里可以根据需要处理查询结果，比如：
      // 1. 关闭抽屉并传递结果给父组件
      // 2. 在抽屉内显示结果
      // 3. 跳转到结果页面

      console.log("对比结果:", response.data);
      // visible.value = false;
    } else {
      ElMessage.error(response.message || "查询失败");
    }
  } catch (error) {
    console.error("对比查询失败:", error);
    ElMessage.error("查询失败，请稍后重试");
  } finally {
    compareLoading.value = false;
  }
};

// 检查项目相关状态
const selectedItem = ref<number>();
const allItems = ref<CompareItemVO[]>([]);
const filteredItems = ref<CompareItemVO[]>([]);
const itemsLoading = ref(false);

// 日期范围选项
const datePeriods = [
  { label: "近1年", value: "1year" },
  { label: "近2年", value: "2year" },
  { label: "近3年", value: "3year" },
  { label: "近5年", value: "5year" },
  { label: "近10年", value: "10year" },
  { label: "自定义时间", value: "custom" }
];

// 当前选中的时间范围
const selectedPeriod = ref("1year");

// 自定义时间范围 - 改为数组格式
const customDateRange = ref<[string, string]>(["", ""]);

// 处理时间范围选择
const handlePeriodChange = (value: string) => {
  selectedPeriod.value = value;

  // 如果不是自定义时间，清空自定义时间选择
  if (value !== "custom") {
    customDateRange.value = ["", ""];
  }
};

// 禁用日期（不能选择未来日期）
const disabledDate = (time: Date) => {
  const today = new Date();
  today.setHours(23, 59, 59, 999);
  return time.getTime() > today.getTime();
};

// 获取检查项目列表
const getCompareItems = async () => {
  try {
    itemsLoading.value = true;
    const response = await reportApi.queryCompareItems({
      userId: props.userId
    });

    if (response.code == 0 && response.data) {
      allItems.value = response.data;
      filteredItems.value = response.data;
    }
  } catch (error) {
    console.error("获取检查项目失败:", error);
    ElMessage.error("获取检查项目失败");
  } finally {
    itemsLoading.value = false;
  }
};

// 前端模糊搜索
const filterItems = (query: string) => {
  if (!query) {
    filteredItems.value = allItems.value;
    return;
  }

  filteredItems.value = allItems.value.filter(item =>
    item.name.toLowerCase().includes(query.toLowerCase())
  );
};
// 监听抽屉打开状态，打开时获取数据
watch(
  () => props.modelValue,
  newValue => {
    if (newValue) {
      console.log("抽屉打开，获取数据");
      getCompareItems();
    }
  }
);

const handleClose = () => {
  visible.value = false;
};
</script>
